package com.like.bluetooth.sample.util

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import com.like.bluetooth.sample.R
import com.like.bluetooth.sample.databinding.DialogFragmentWriteDataBinding
import com.like.bluetooth.util.isHexString
import com.like.bluetooth.util.toByteArray
import com.like.common.base.BaseDialogFragment

class WriteDataFragment : BaseDialogFragment() {
    private lateinit var mBinding: DialogFragmentWriteDataBinding
    var callback: ((data: ByteArray) -> Unit)? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.dialog_fragment_write_data, container, false)
        return mBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mBinding.btnConfirm.setOnClickListener {
            val data = mBinding.etData.text.toString().trim()
            if (data.isHexString() && data.length % 2 == 0) {
                callback?.invoke(data.toByteArray())
                dismiss()
            } else {
                Toast.makeText(context, "只能输入16进制的数据", Toast.LENGTH_SHORT).show()
            }
        }
    }

    override fun initLayoutParams(layoutParams: WindowManager.LayoutParams) {
        super.initLayoutParams(layoutParams)
        resources.displayMetrics?.widthPixels?.let { screenWidth ->
            // 宽高
            layoutParams.width = (screenWidth * 0.9).toInt()
        }
    }

}